﻿// This class was planned to be used for piping between the KISS Konsole and StationConsole, but the KISS Konsole was replaced by PowerSDR (due to KISS Konsole requiring an FPGA board)
using System.IO;
using System.Text;
using System;
public class StreamString
{
    private Stream ioStream;
    private UnicodeEncoding streamEncoding;

    public StreamString(Stream ioStream)
    {
        this.ioStream = ioStream;
        streamEncoding = new UnicodeEncoding();
    }

    public string ReadString()
    {
        int len;
        byte[] inBuffer = { (byte)0, (byte)0 };
        if ((len = ioStream.ReadByte() * 256) != -256)
        {
            len += ioStream.ReadByte();
            inBuffer = new byte[len];
            ioStream.Read(inBuffer, 0, len);
        }
        else
        {
            Console.WriteLine("Server sent nothing back");
        }
        return streamEncoding.GetString(inBuffer);
    }

    public int WriteString(string outString)
    {
        byte[] outBuffer = streamEncoding.GetBytes(outString);
        int len = outBuffer.Length;
        if (len > UInt16.MaxValue)
        {
            len = (int)UInt16.MaxValue;
        }
        ioStream.WriteByte((byte)(len / 256));
        ioStream.WriteByte((byte)(len & 255));
        ioStream.Write(outBuffer, 0, len);
        ioStream.Flush();

        return outBuffer.Length + 2;
    }
}
